package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.common.MiPushUtils;
import com.api.shopapi.config.RoleConfig;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.Error;
import com.api.shopapi.entity.dto.BusinessDTO;
import com.api.shopapi.entity.dto.NursingRecordPositionDTO;
import com.api.shopapi.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.api.shopapi.config.AppPushConfig.app_packName;
import static com.api.shopapi.config.AppPushConfig.mi_app_secret;

@RestController
public class RealTimeController extends BaseController {


    @Autowired
    @Qualifier("ErrorServiceImplOne")
    private ErrorService errorService;


    @Autowired
    @Qualifier("GovernmentServiceImplOne")
    private GovernmentService governmentService;

    @Autowired
    @Qualifier("BusinessServiceImplOne")
    private BusinessService businessService;


    @Autowired
    @Qualifier("OrderBusinessServiceImplOne")
    private OrderBusinessService orderBusinessService;


    @Autowired
    @Qualifier("TotalOrderDayServiceImplOne")
    private TotalOrderDayService totalOrderDayService;


    @Autowired
    @Qualifier("TotalOrderMonthServiceImplOne")
    private TotalOrderMonthService totalOrderMonthService;


    @Autowired
    @Qualifier("TotalOrderYearServiceImplOne")
    private TotalOrderYearService totalOrderYearService;


    @Autowired
    @Qualifier("NursingRecordServiceImplOne")
    private NursingRecordService nursingRecordService;

    @Autowired
    @Qualifier("MedicinerServiceImplOne")
    private MedicinerService medicinerService;

    @Autowired
    @Qualifier("NurseServiceImplOne")
    private NurseService nurseService;

    @Autowired
    @Qualifier("NurseAideServiceImplOne")
    private NurseAideService nurseAideService;

    @Autowired
    @Qualifier("UserAppInfoServiceImplOne")
    private UserAppInfoService userAppInfoService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;


    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;


    @Autowired
    @Qualifier("InstitutionServiceImplOne")
    private InstitutionService institutionService;


    @Autowired
    @Qualifier("NursingRecordPositionServiceImplOne")
    private NursingRecordPositionService nursingRecordPositionService;


    @Autowired
    @Qualifier("NursingRecordPositionLackServiceImplOne")
    private NursingRecordPositionLackService nursingRecordPositionLackService;




    /**
     * ==========================================
     * */

    //每30秒执行一次,把错误文件插入数据库
    @Scheduled(cron = "30 * * * * ?")
    public void insertError(){

        //System.out.println(startTimeYesterday());
        //System.out.println(endTimeYesterday());


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            File file = new File(errorPath);

            if (file.exists()){

                File[] files = file.listFiles();
                if (null == files || files.length == 0) {
//                    System.out.println(errorPath + "---------------文件夹是空的!");




                }else {
                    for (int i = 0; i < files.length; i++){
                        String filePath =errorPath+"\\"+files[i].getName();
                        File file1 = new File(filePath);

                        FileInputStream fileInputStream = new FileInputStream(file1);
                        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                        StringBuffer sb = new StringBuffer();
                        String text = null;
                        while((text = bufferedReader.readLine()) != null){
                            sb.append(text);
                        }


                        String content=sb.toString();
                        String[] error=content.split("!");

                        String url=error[0];
                        String param=error[1];
                        String message=error[2];
                        String type=error[3];

                        Error error1 =new Error();
                        error1.setErrorCode(UUID.randomUUID().toString());
                        error1.setUrl(url);
                        error1.setParam(param);
                        error1.setMessage(message);
                        error1.setType(type);
                        error1.setCreateTime(new Date());

                        errorService.insert(error1);
                        fileInputStream.close();
                        inputStreamReader.close();
                        bufferedReader.close();
                        deleteFile(filePath);
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * ==========================================
     * */


    //每天1点10分30秒触发任务,统计商家昨天的订单信息，插入数据库
    @Scheduled(cron = "30 10 1 * * ?")
    public void insertTotalOrderDay(){
        try {

            List<Government> listGovernment = governmentService.getList();
            for(Government government:listGovernment){
                List<BusinessDTO> listBusinessDTO =
                        businessService.getListBusinessDTOByGovernmentCode(government.getGovernmentCode());

                for(BusinessDTO businessDTO:listBusinessDTO){
                    List<OrderBusiness> listOrderBusiness =
                            orderBusinessService.ListYesterday(businessDTO.getBusinessCode(),startTimeYesterday(),endTimeYesterday());

                    int orderBusinessCount = listOrderBusiness.size();
                    double orderBusinessTotal = totalMoney(listOrderBusiness);

                    TotalOrderDay totalOrderDay = new TotalOrderDay();
                    totalOrderDay.setTotalOrderDayCode(UUID.randomUUID().toString());
                    totalOrderDay.setYear((new Date().getYear()+1900)+"");
                    totalOrderDay.setMonth((new Date().getMonth()+1)+"");
                    totalOrderDay.setDay(new Date().getDate()+"");
                    totalOrderDay.setOrderMoney(orderBusinessTotal);
                    totalOrderDay.setOrderCount(orderBusinessCount);
                    totalOrderDay.setCreateTime(new Date());
                    totalOrderDay.setBusinessCode(businessDTO.getBusinessCode());
                    totalOrderDayService.insert(totalOrderDay);

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //每月1号2点10分30秒触发任务,统计商家每月的订单信息，插入数据库
    @Scheduled(cron = "30 10 2 1 * ?")
    public void insertTotalOrderMonth(){
        try {

            List<Government> listGovernment = governmentService.getList();
            for(Government government:listGovernment){
                List<BusinessDTO> listBusinessDTO =
                        businessService.getListBusinessDTOByGovernmentCode(government.getGovernmentCode());

                for(BusinessDTO businessDTO:listBusinessDTO){

                    List<TotalOrderDay> listTotalOrderDay =
                            totalOrderDayService.ListThisMonth(businessDTO.getBusinessCode(),
                                    (new Date().getMonth()+1)+"");

                    int count = totalMonthCount(listTotalOrderDay);
                    double money = totalMonthMoney(listTotalOrderDay);

                    TotalOrderMonth totalOrderMonth = new TotalOrderMonth();
                    totalOrderMonth.setTotalOrderMonthCode(UUID.randomUUID().toString());
                    totalOrderMonth.setYear((new Date().getYear()+1900)+"");
                    totalOrderMonth.setMonth((new Date().getMonth()+1)+"");
                    totalOrderMonth.setOrderCount(count);
                    totalOrderMonth.setOrderMoney(money);
                    totalOrderMonth.setCreateTime(new Date());
                    totalOrderMonth.setBusinessCoe(businessDTO.getBusinessCode());
                    totalOrderMonthService.insert(totalOrderMonth);

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //每年1月1号3点10分30秒触发任务,统计商家每年的订单信息，插入数据库
    @Scheduled(cron = "30 10 3 1 1 ?")
    public void insertTotalOrderYear(){
        try {

            List<Government> listGovernment = governmentService.getList();
            for(Government government:listGovernment){
                List<BusinessDTO> listBusinessDTO =
                        businessService.getListBusinessDTOByGovernmentCode(government.getGovernmentCode());

                for(BusinessDTO businessDTO:listBusinessDTO){

                    List<TotalOrderMonth> listTotalOrderMonth =
                            totalOrderMonthService.ListThisYear(businessDTO.getBusinessCode(),
                                    (new Date().getYear()+1900)+"");

                    int count = totalYearCount(listTotalOrderMonth);
                    double money = totalYearMoney(listTotalOrderMonth);

                    TotalOrderYear totalOrderYear = new TotalOrderYear();
                    totalOrderYear.setTotalOrderYearCode(UUID.randomUUID().toString());
                    totalOrderYear.setOrderCount(count);
                    totalOrderYear.setOrderMoney(money);
                    totalOrderYear.setYear((new Date().getYear()+1900)+"");
                    totalOrderYear.setCreateTime(new Date());
                    totalOrderYear.setBusinessCode(businessDTO.getBusinessCode());
                    totalOrderYearService.insert(totalOrderYear);

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    //昨天的起始时间
    public Date startTimeYesterday(){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dd = sdf.format(new Date());
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(sdf.parse(dd));
            calendar.add(calendar.DATE, -1);
            return calendar.getTime();
        }catch (Exception e){
            e.printStackTrace();
            return new Date();
        }
    }

    //昨天的结束时间
    public Date endTimeYesterday(){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dd = sdf.format(new Date());
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(sdf.parse(dd));
            return calendar.getTime();
        }catch (Exception e){
            e.printStackTrace();
            return new Date();
        }
    }

    //获取总价
    public double totalMoney(List<OrderBusiness> list){
        double d = 0;
        for(OrderBusiness orderBusiness:list){
            OrderBusiness orderBusiness1 =
                    orderBusinessService.getByOrderBusinessCode(orderBusiness.getOrderBusinessCode());
            d+= orderBusiness1.getPrice();
        }
        return d;
    }


    //获取月总数
    public int totalMonthCount(List<TotalOrderDay> list){
        int d = 0;
        for(TotalOrderDay totalOrderDay:list){
            d+= totalOrderDay.getOrderCount();
        }
        return d;
    }

    //获取月总价
    public double totalMonthMoney(List<TotalOrderDay> list){
        double d = 0;
        for(TotalOrderDay totalOrderDay:list){
            d+= totalOrderDay.getOrderMoney();
        }
        return d;
    }

    //获取年总数
    public int totalYearCount(List<TotalOrderMonth> list){
        int d = 0;
        for(TotalOrderMonth totalOrderMonth:list){
            d+= totalOrderMonth.getOrderCount();
        }
        return d;
    }

    //获取年总价
    public double totalYearMoney(List<TotalOrderMonth> list){
        double d = 0;
        for(TotalOrderMonth totalOrderMonth:list){
            d+= totalOrderMonth.getOrderMoney();
        }
        return d;
    }

    /**
     * ==========================================
     * */


    //每30秒执行一次,把即将打卡的文件插入数据库，并推送手机消息
    @Scheduled(cron = "30 * * * * ?")
    public void pushNofity(){

        String nursingPath = push+File.separator+"nursing";
        String nurisngWillPush = nursingPath+File.separator+"willPush";

        try {
            File file = new File(nurisngWillPush);

            if (file.exists()){

                File[] files = file.listFiles();
                if (null == files || files.length == 0) {
                //System.out.println(errorPath + "---------------文件夹是空的!");


                }else {
                    for (int i = 0; i < files.length; i++){

                        String fileName = files[i].getName();
                        String spanTime = fileName.substring(0,fileName.indexOf("."));

                        System.out.println("spanTime:"+spanTime);

                        Date now = new Date();
                        Date d = new Date(Long.parseLong(spanTime));

                        //间隔小于一分钟
                        if(d.getTime() - now.getTime() < 10*60*1000 ){

                            String filePath =files[i].getPath();
                            File file1 = new File(filePath);

                            //read file
                            FileInputStream fileInputStream = new FileInputStream(file1);
                            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                            StringBuffer sb = new StringBuffer();
                            String text = null;
                            while((text = bufferedReader.readLine()) != null){
                                sb.append(text);
                            }
                            fileInputStream.close();
                            inputStreamReader.close();
                            bufferedReader.close();


                            String content=sb.toString();

                            JSONObject jsonObject1 = JSONObject.parseObject(content);
                            String nursingRecordCode = jsonObject1.getString("nursingRecordCode");
                            String nursingRecordCodePath = nursingPath+File.separator+nursingRecordCode;

                            //insert wait position
                            NursingRecordPosition nursingRecordPosition = new NursingRecordPosition();
                            nursingRecordPosition.setNursingRecordPositionCode(UUID.randomUUID().toString());
                            nursingRecordPosition.setNursingRecordCode(nursingRecordCode);
                            nursingRecordPosition.setCreateTime(new Date());
                            nursingRecordPositionService.insert(nursingRecordPosition);


                            try{

                                String minFileName = getMinFileName(nursingRecordCodePath);

                                //push notify
                                push(nursingRecordCode,minFileName);


                                //move file
                                //String minFileName = getMinFileName(nursingRecordCodePath);
                                File startFile=new File(nursingRecordCodePath+File.separator+minFileName);
                                File endFile=new File(nurisngWillPush+File.separator+minFileName);
                                if (startFile.renameTo(endFile)) {
                                    System.out.println("文件移动成功！目标路径：{"+endFile.getAbsolutePath()+"}");
                                } else {
                                    System.out.println("文件移动失败！起始路径：{"+startFile.getAbsolutePath()+"}");
                                }

                            }catch (Exception e){
                                e.printStackTrace();
                            }

                            //delete pushed file
                            deleteFile(filePath);

                        }

                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //获取文件里文件名称最小的文件名
    String getMinFileName(String fdPath){

        String minFileName = "";
        try {
            File file = new File(fdPath);

            if (file.exists()){

                File[] files = file.listFiles();
                if (null == files || files.length == 0) {
                    //System.out.println(errorPath + "---------------文件夹是空的!");


                }else {
                    long k = 100000000000000000L;// Long.parseLong("100000000000000000");
                    for (int i = 0; i < files.length; i++){

                        String fileName = files[i].getName();
                        String spanTime = fileName.substring(0,fileName.indexOf("."));

                        long dd = Long.parseLong(spanTime);
                        if(dd<k){
                            k = dd;
                            minFileName = fileName;
                        }

                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return minFileName;
    }

    //推送
    private void push(String nursingRecordCode,String fileName){

        NursingRecord nursingRecord = nursingRecordService.getByNursingRecordCode(nursingRecordCode);

        String recordType = nursingRecord.getRecordType();
        String regId = "";
        String appOs = "";
        if(recordType.equals("mediciner")){
            Mediciner mediciner = medicinerService.getByMedicinerCode(nursingRecord.getMedicinerCode());
            UserAppInfo userAppInfo = userAppInfoService.getByUserCode(mediciner.getUserCode());
            regId = userAppInfo.getRegId();
            appOs = userAppInfo.getAppOs();
        }
        if(recordType.equals("nurse")){
            Nurse nurse = nurseService.getByNurseCode(nursingRecord.getNurseCode());
            UserAppInfo userAppInfo = userAppInfoService.getByUserCode(nurse.getUserCode());
            regId = userAppInfo.getRegId();
            appOs = userAppInfo.getAppOs();
        }
        if(recordType.equals("nurseAide")){
            NurseAide nurseAide = nurseAideService.getByNurseAideCode(nursingRecord.getNurseAideCode());
            UserAppInfo userAppInfo = userAppInfoService.getByUserCode(nurseAide.getUserCode());
            regId = userAppInfo.getRegId();
            appOs = userAppInfo.getAppOs();
        }


        if(appOs.equals("xiaomi")|| appOs.equals("other")){
            org.json.simple.JSONObject jsonObjectPayload = new org.json.simple.JSONObject();
            jsonObjectPayload.put("fileName", fileName);
            jsonObjectPayload.put("type", "serveClockIn");
            miPush("例行服务打卡","服务中不定时打卡",jsonObjectPayload,regId);
        }
        if(appOs.equals("huawei")){

        }
        if(appOs.equals("oppo")){

        }
        if(appOs.equals("vivo")){

        }


    }

    //小米推送
    private void miPush(String title, String content, org.json.simple.JSONObject jsonObject,String regId){
        try {

            MiPushUtils obj = new MiPushUtils(mi_app_secret,app_packName,"",1);

            //obj.sendMessageToRegId("title","content",null,"regId",1,1);

            obj.sendMessageToRegIdOther(title,content,jsonObject,regId,0,1);

        }catch(Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * ==========================================
     * */

    //每30秒执行一次,更新超时的未打卡记录
    @Scheduled(cron = "30 * * * * ?")
    public void positionClockInOvertime(){
        List<NursingRecordPosition> list = nursingRecordPositionService.listOvertime();
        System.out.println("positionClockInOvertime:"+list.size());
        for(NursingRecordPosition nursingRecordPosition:list){
            nursingRecordPosition.setIsOvertime(1);
            nursingRecordPositionService.update(nursingRecordPosition);
        }
    }

    //每30秒执行一次,把未打卡记录写入lack表
    @Scheduled(cron = "30 * * * * ?")
    public void writeNotClockInToLack(){
        List<NursingRecordPosition> list = nursingRecordPositionService.listNotAddLack();
        System.out.println("writeNotClockInToLack:"+list.size());
        for(NursingRecordPosition nursingRecordPosition:list){


            nursingRecordPosition.setIsAddLack(1);
            nursingRecordPositionService.update(nursingRecordPosition);

            NursingRecord nursingRecord =
                    nursingRecordService.getByNursingRecordCode(nursingRecordPosition.getNursingRecordCode());
            if(nursingRecord.getStatus() != 1){
                continue;
            }

            Institution institution = institutionService.getByInstitutionCode(nursingRecord.getInstitutionCode());

            NursingRecordPositionLack nursingRecordPositionLack = new NursingRecordPositionLack();
            nursingRecordPositionLack.setNursingRecordPositionLackCode(UUID.randomUUID().toString());
            nursingRecordPositionLack.setNursingRecordPositionCode(nursingRecordPosition.getNursingRecordPositionCode());
            nursingRecordPositionLack.setCreateTime(new Date());
            nursingRecordPositionLack.setInstitutionCode(nursingRecord.getInstitutionCode());
            nursingRecordPositionLack.setGovernmentCode(institution.getGovernmentCode());
            nursingRecordPositionLackService.insert(nursingRecordPositionLack);


            //write file
            String fdPath= push +File.separator + "clockIn";
            File file=new File(fdPath);
            if(!file.exists()){
                file.mkdirs();
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("nursingRecordPositionLackCode",nursingRecordPositionLack.getNursingRecordPositionLackCode());
            jsonObject.put("nursingRecord",nursingRecord);
            jsonObject.put("type",13);
            try{
                ObjectMapper mapper=new ObjectMapper();
                mapper.writeValue(new File(fdPath +File.separator + new Date().getTime() + ".txt"),jsonObject);

                String govCode = nursingRecordPositionLack.getGovernmentCode();
                Role role = roleService.getByName(RoleConfig.governmentRoleName);

                //为各个后台账号写报警文件
                List<Staff> staffList = staffService.getByGovernmentCodeAndRoleCode(govCode, role.getRoleCode());
                for (Staff staff : staffList) {
                    String fdPath2= pushAlarmPath+"\\" + staff.getStaffCode();
                    File fileStaff=new File(fdPath2);
                    if(!fileStaff.exists()){
                        fileStaff.mkdirs();
                    }
                    mapper.writeValue(new File(fdPath2 + "\\nursing" + new Date().getTime() + ".txt"),jsonObject);
                }


            }catch (Exception e){
                e.printStackTrace();
            }



        }
    }


    /**
     * ==========================================
     * */


}
